package com.zl.learning.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestInterrupted {
    static class T1 extends Thread {
        private boolean start = true;

        @Override
        public void run() {
            while (start) {
                for (int i = 0; i < 10; i++) {
                    System.out.println("I'm running ...." + i);
                }
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
//                    start = false;
                    System.out.println("I'm be interruped.");
                }
            }
        }

        public void shutdown() {
            this.start = false;
            this.interrupt();
        }
    }

    static class T2 implements Runnable {
        private Thread t;
        private boolean start = true;

        @Override
        public void run() {
            t = Thread.currentThread();
            while (start) {
                for (int i = 0; i < 10; i++) {
                    System.out.println("I'm running ...." + i);
                }
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    System.out.println("I'm be interruped.");
                    this.start = false;
                }
            }
        }

        public void stop() {
            this.start = false;
            t.interrupt();
        }

    }

    public static class Test1 {
        public static void main(String[] args) throws InterruptedException {
            T1 t1 = new T1();
            t1.start();
            TimeUnit.SECONDS.sleep(1);
            t1.shutdown();
            System.out.println("t1 is interrupted.");
        }
    }

    public static class Test2 {
        public static void main(String[] args) throws InterruptedException {
            T2 t2 = new T2();
            new Thread(t2).start();
            TimeUnit.MILLISECONDS.sleep(1);
            t2.stop();
            System.out.println("t2 is interrupted.");
        }
    }

    public static class Test3 {
        public static void main(String[] args) throws InterruptedException {

            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.execute(() -> {
                boolean start = true;
                while (start) {
                    try {
                        System.out.println("HelloWorld");
                        Thread.sleep(90);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        start = false;
                    }
                }
            });

            Thread.sleep(1000);
            executorService.shutdownNow();
            System.out.println("线程池关闭");
        }
    }
}
